// components/process-bar/index.js
let movableAreaWidth = 0
let movableViewWidth = 0
const backgroundAudioManager = wx.getBackgroundAudioManager()
let currentSec = -1 //当前的秒数
let duration=0 //当前歌曲的总时长
Component({
  /**
   * 组件的属性列表
   */
  properties: {

  },

  /**
   * 组件的初始数据
   */
  data: {
    showTime: {
      currentTime: '00:00',
      totalTime: '00:00'
    },
    movableDis: 0, //移动的距离
    progress: 0, //当前进度条移动距离
  },
  lifetimes: {
    ready() {
      this._getMovableDis()
      this._bindBGMEvent()
    }
  },
  /**
   * 组件的方法列表
   */
  methods: {
    onChange(event){
      console.log(event);
      if(event.detail.source=='touch'){
        //这样设置只会存储，不会设置到页面上
        this.data.progress = event.detail.x/(movableAreaWidth-movableViewWidth)*100;
        this.data.movableDis=event.detail.x;
      }
    },
    onTouchEnd(){

      const currentTimeFmt=this._dateFormat(Math.floor(backgroundAudioManager.currentTime))
        this.setData({
          progress:this.data.progress,
          movableDis: this.data.movableDis,
          ['showTime.current']: currentTimeFmt.min+":"+currentTimeFmt.sec
        })
        //设置歌曲进度
        backgroundAudioManager.seek(duration*this.data.progress / 100)
    },
    _getMovableDis() {
      const query = this.createSelectorQuery(); //如果在Page里面，需要用 wx.createSelectorQuery()
      query.select('.movable-area').boundingClientRect()
      query.select('.movable-view').boundingClientRect()
      query.exec((rect) => {
        movableAreaWidth = rect[0].width,
          movableViewWidth = rect[1].width
      })
    },
    _bindBGMEvent() {
      backgroundAudioManager.onPlay(() => {
        console.log('onPlay');
      })
      backgroundAudioManager.onStop(() => {
        console.log('onStop');
      })
      backgroundAudioManager.onPause(() => {
        console.log('onPause');
      })
      backgroundAudioManager.onWaiting(() => {
        console.log('onWaiting');
      })
      backgroundAudioManager.onCanplay(() => {
        console.log('onCanplay');
        console.log(backgroundAudioManager.duration); //背景音乐的总时长
        // if(backgroundAudioManager.duration===undefined){
        if (typeof backgroundAudioManager.duration != 'undefined') {
          this._setTime()
        }else{
          setTimeout(()=>{
            this._setTime()
          },1000)
        }
      })
      backgroundAudioManager.onTimeUpdate(() => {
        // console.log('onTimeUpdate');

        //获取当前已经播放的时间
        const currentTime=backgroundAudioManager.currentTime;
        //获取播放总时长
        const duration=backgroundAudioManager.duration;
     
        if(currentTime.toString().split(".")[0]!=currentSec){
          // console.log(currentTime);
          const currentTimeFmt=this._dateFormat(currentTime);
          this.setData({
            movableDis:(movableAreaWidth-movableViewWidth)*currentTime/duration,
              progress: currentTime/duration*100,
              ['showTime.currentTime']: `${currentTimeFmt.min}:${currentTimeFmt.sec}`
          })
          currentSec=currentTime.toString().split(".")[0];
        }
      })
      backgroundAudioManager.onEnded(() => {
        console.log('onEnded');
      })
      backgroundAudioManager.onError((res) => {
        console.log(res.errMsg);
        console.log(res.errCode)
        wx.showToast({
          title: '错误:' + res.errCode,
        });
      })

    },
    _setTime(){
      duration=backgroundAudioManager.duration
      // console.log(duration);
      const durationFmt=this._dateFormat(duration);
      // console.log(duration,durationFmt);
      this.setData({
        // 给对象中的某一个属性赋值
        ['showTime.totalTime']:durationFmt.min+":"+durationFmt.sec
      })
    },
    //格式化时间
    _dateFormat(sec){
      //分钟
      const min = Math.floor(sec/60);
      sec=Math.floor(sec%60);
      return {
        "min":this._parse0(min),
        "sec":this._parse0(sec)
      }
    },
    _parse0(sec){
      return sec<10?'0'+sec:sec
    }
  }
})